<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ShareController extends Controller
{
    /**
     * 微信分享配置
     *
     * @param Request $request
     * @param int $url
     * @return \Illuminate\Http\JsonResponse
     */
    public function share(Request $request)
    {
        $url = 'http://my.12371.cn/index';
        $jsapiTicket = $this->getJsApiTicket();
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=".$jsapiTicket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;


        $signature = sha1($string);

        $signPackage = [
            "appId" => 'wx6da356280dc66b00',
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        ];

        return response()->json(['code' => '200', 'message' => 'success','data' => $signPackage]);
    }


    public function curlGet($url) {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }

    public function curlPost($url,$data){
        //以'json'格式发送post的https请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        $output = curl_exec($curl);
        curl_close($curl); // 关闭CURL会话
        return $output;
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    private function getJsApiTicket()
    {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = DB::table('share_config')->where('id',1)->first();
        
        $jsapi_ticket = $data->jsapi_ticket;
        $ticket_expire_time = $data->ticket_expire_time;

        
        if (!empty($jsapi_ticket) ||  $ticket_expire_time < time()) {
            $accessToken = $this->getAccessToken();
            //定义传递的参数数组
            $params['type'] = 'jsapi';
            $params['access_token'] = $accessToken;
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $params['access_token'] . "&type=" . $params['type'] . "";
            $res = json_decode($this->curlGet($url),true);
            $ticket = isset($res['ticket']) ? $res['ticket'] : NULL;
            if ($ticket) {
                $arr['ticket_expire_time'] = time() + 7000;
                $arr['jsapi_ticket'] = $ticket;
                DB::table('share_config')->where('id',1)->update($arr);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        
        return $ticket;
    }
    private function getAccessToken()
    {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = DB::table('share_config')->where('id',1)->first();
        $access_token_s = $data->access_token;
        $token_expire_time = $data->token_expire_time;
        if (empty($access_token_s) || $token_expire_time < time()) {
            //定义传递的参数数组
            $params['grant_type'] = 'client_credential';
            $params['appid'] = 'wx6da356280dc66b00';
            $params['secret'] = '6a3fc7fc2eae647230162f0b97989ad9';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=".$params['grant_type']."&appid=".$params['appid']."&secret=".$params['secret']."";
            $res = json_decode($this->curlPost($url, $params),true);
            $access_token = isset($res['access_token']) ? $res['access_token'] : NULL;
            if ($access_token) {
                $arr['token_expire_time'] = time() + 7000;
                $arr['access_token'] = $access_token;

                DB::table('share_config')->where('id',1)->update($arr);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }


}
